package com.MR;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 需求：读取HDFS上的hello.txt文件，
 * 只有Map阶段，没有Reduce阶段
 */
public class WordCountJobNoReduce {
    //1.Map阶段--自定义Mapper类，继承Mapper类，重写map()函数
    public static class MyMapper extends Mapper<LongWritable, Text,Text,LongWritable>{
        //打印日志信息
        Logger logger=LoggerFactory.getLogger(MyMapper.class);
        //map函数可以接收<key1,value1>生成<key2,value2>
        @Override
        protected void map(LongWritable key1, Text value1, Mapper<LongWritable, Text, Text, LongWritable>.Context context)
                throws IOException, InterruptedException {
            logger.info("<key1,value1>=<"+key1.get()+","+value1.toString()+">");
            //key1--每一行数据的行首偏移量；value1---每一行的内容
            //1.将每一行数据转换成字符串然后进行切割
            String [] words=value1.toString().split(" ");
            //2.遍历字符数组，迭代所有的单词
            for (String word:words) {
                //3.把单词组装成<key2,value2>的形式
                Text key2=new Text(word);
                LongWritable value2=new LongWritable(1L);
                //4.将<key2,value2>写出去
                context.write(key2,value2);
            }
        }
    }

    //3.组装Job阶段（Map+Reduce）
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {

        //如果传入的参数不够，程序直接退出
        if (args.length!=2)
            System.exit(100);
        //3.1:创建一个Job对象
        Job job=Job.getInstance(new Configuration());
        //必须设置：否则在集群中找不到WordCountJob这个类
        job.setJarByClass(WordCountJobNoReduce.class);

        //3.2：指定Job的输入路径（目录或者文件）
        FileInputFormat.setInputPaths(job,new Path(args[0]));
        //3.3:指定job的输出路径
        FileOutputFormat.setOutputPath(job,new Path(args[1]));

        //3.4：将Mapper添加到Job中
        job.setMapperClass(MyMapper.class);
        job.setMapOutputKeyClass(Text.class);//指定输出<key2,value2>类型
        job.setMapOutputValueClass(LongWritable.class);

        //3.5设置Reduce为禁用--将Reduce的Task设置为0--表示不需要Reduce阶段
        job.setNumReduceTasks(0);
        //3.6：提交job
        job.waitForCompletion(true);
    }
}
